//
//  SEGDigitalCommunity2HouseInfoViewModel.m
//  SEGViewModel
//
//  Created by 山刘 on 2020/6/22.
//

#import "SEGDigitalCommunity2LandlordViewModel.h"

@interface SEGDigitalCommunity2LandlordViewModel()
@property (nonatomic, strong, readwrite) RACCommand *nextStepCommand;
@property (strong, nonatomic, readwrite) RACSubject *messageSubject;

@property (nonatomic, assign,readwrite) BOOL codeButtonEnabled;
@property (nonatomic, copy,readwrite) NSString* codeButtonTitleString;
@property (nonatomic, strong, readwrite) RACCommand *verificationCodeCommand;

@property (nonatomic, strong, readwrite) RACCommand *ownerAuthorCommand;
@end

@implementation SEGDigitalCommunity2LandlordViewModel
#pragma mark - Init
-(instancetype)init{
    if (self = [super init]) {
        _codeButtonTitleString = @"获取验证码";
        _codeButtonEnabled = YES;
        [self racInit];
    }
    return self;
}

-(void)dealloc{
    [self.nextStepCommand rac_deallocDisposable];
    [self.messageSubject rac_deallocDisposable];
}

- (void)racInit {
    
    @weakify(self);
    
    _nextStepCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSString*  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            
            [self.messageSubject sendNext:@{@"type":@"1",@"value":@"验证中"}];
            
            self.userName = [self.userName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            
            [SEGQuerycustomerlistbyhouseidManager destroyResource];
            [[SEGQuerycustomerlistbyhouseidManager sharedManager] requestQuerycustomerlistbyhouseidWithHouseid:self.houseId finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                
                if (!isSuccessed) {
                    [self.messageSubject sendNext:@{@"type":@"2",@"value":errorMessage}];
                    [subscriber sendCompleted];
                    return;
                }
                
                // 遍历查找是否有符合条件的业主信息
                NSArray<SEGQuerycustomerlistbyhouseidResultlistModel*>* resultList = [SEGQuerycustomerlistbyhouseidManager sharedManager].queryCustomerListByHouseId.data.resultList;
                SEGQuerycustomerlistbyhouseidResultlistModel* CusInfo;
                for (SEGQuerycustomerlistbyhouseidResultlistModel *object in resultList) {
                    
                    if ([object.custName isEqualToString:self.userName] &&
                        object.custCard &&
                        object.custCard.length > 6 &&
                        [[object.custCard substringFromIndex:object.custCard.length - 6] isEqualToString:self.PersonalIdLastSix]) {
                        CusInfo = object;
                        break;
                    }
                }
                if (!CusInfo) {
                    [self.messageSubject sendNext:@{@"type":@"2",@"value":@"找不到业主信息"}];
                    [subscriber sendCompleted];
                    return;
                }
                
                // 判断业主是否已认证
                [[SEGQueryisauthManager sharedManager] requestQueryisauthWithHouseid:self.houseId communityId:kAccountCommunityID custType:@"1000" finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    
                    if (![codeType isEqualToString:@"0"]) {
                        NSString *msg = [self messageFromCode:codeType];
                        if (!msg || msg.length <=0) {
                            msg = errorMessage;
                        }
                        [self.messageSubject sendNext:@{@"type":@"2",@"value":msg}];
                        [subscriber sendCompleted];
                        return;
                    }
                    
                    NSDictionary *temptDic = [CusInfo yy_modelToJSONObject];
                    self.CusInfo = [SEGQuerycustomerlistbyhouseidResultlistModel yy_modelWithJSON:temptDic];
                    [self.messageSubject sendNext:@{@"type":@"3",@"value":@"验证成功"}];
                    [subscriber sendNext:nil];
                    [subscriber sendCompleted];
                }];
            }];
            return [RACDisposable disposableWithBlock:^{
            }];
        }];
    }];
    
    // 获取短信验证码
    _verificationCodeCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSNumber*  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            @strongify(self);
            
            NSString *tel = [NSString string];
            if ([input integerValue] == SEGCusAuthorVerificationCodeTypeDefault) {
                tel = self.CusInfo.custTel;
                [self sendSMSWithType:[input integerValue] tel:tel didSubscribe:subscriber];
            }
            if ([input integerValue] == SEGCusAuthorVerificationCodeTypeNewTel) {
                tel = self.cusNewTel;
                
                // 更换前后的手机号码不能相同
                if ([self.cusNewTel isEqualToString:self.CusInfo.custTel]) {
                    [self.messageSubject sendNext:@{@"type":@"2",@"value":@"不能绑定相同手机号"}];
                    [subscriber sendCompleted];
                    return nil;
                }
                
                [self.messageSubject sendNext:@{@"type":@"4",@"value":@""}];
                
                [[SEGQuerycustomertelexistManager sharedManager] requestQuerycustomertelexistWithCommunityid:self.CusInfo.communityId
                                                                                                    custCard:self.CusInfo.custCard
                                                                                                         tel:self.cusNewTel
                                                                                                      custId:self.CusInfo.custId
                                                                                                    finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    
                    if (!isSuccessed) {
                        [self.messageSubject sendNext:@{@"type":@"2",@"value":errorMessage}];
                        [subscriber sendCompleted];
                        return;
                    }
                    [self.messageSubject sendNext:@{@"type":@"0",@"value":@""}];
                    [self sendSMSWithType:[input integerValue] tel:tel didSubscribe:subscriber];
                }];
            }
            [subscriber sendCompleted];
            
            return [RACDisposable disposableWithBlock:^{
            }];
        }];
    }];
    
    // APP端-业主认证（）
    _ownerAuthorCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSNumber*  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            @strongify(self);
            
            SEGQuerycustomerlistbyhouseidResultlistModel *data = self.CusInfo;
            
            NSString *tel = @"";
            if (input && [input integerValue] == SEGCusAuthorVerificationCodeTypeNewTel) {
                tel = self.cusNewTel;
            }else{
                tel = data.custTel;
            }
            
            [[SEGSubmitpropertyownerauthManager sharedManager] requestSubmitpropertyownerauthWithCustid:data.custId
                                                                                                    tel:tel
                                                                                               custName:data.custName
                                                                                            communityId:data.communityId
                                                                                                houseId:self.houseId
                                                                                                cardNbr:data.custCard
                                                                                             custGender:data.custGender
                                                                                           businessCode:@"C_PROPERTY_AUTH"
                                                                                                smsCode:self.verificationCode
                                                                                               finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                
                if (!isSuccessed) {
                    [self.messageSubject sendNext:@{@"type":@"2",@"value":errorMessage}];
                }else{
                    [subscriber sendNext:nil];
                }
                [subscriber sendCompleted];
            }];
            
            return [RACDisposable disposableWithBlock:^{
            }];
        }];
    }];
}

#pragma mark - Publish Methods

/// 判断申请认证的手机号是否匹配
/// @param inputLastText 手机号后四位
-(BOOL)checkTelInputStatus:(NSString*)inputLastText{
    if (inputLastText && inputLastText.length == 4) {
        if (self.CusInfo && self.CusInfo.custTel && self.CusInfo.custTel.length >= 11) {
            if ([[self.CusInfo.custTel substringFromIndex:self.CusInfo.custTel.length - 4] isEqualToString:inputLastText]) {
                return YES;
            }
        }
    }
    return NO;
}

/// 监听更新手机号提交按钮的可点击状态
-(void)checkChangeCusTelConfirmButtonStatus {
    // 确认提交 按钮是否可以点击
    RAC(self,cusNewTelConfirmButtonEnabled) = [RACSignal combineLatest:@[RACObserve(self, cusNewTel),RACObserve(self, verificationCode)] reduce:^id (NSString *cusNewTel,NSString *verificationCode){
        
        BOOL checkCusNewTel = NO;
        if (cusNewTel && cusNewTel.length == 11) {
            checkCusNewTel = YES;
        }
        
        BOOL checkVerificationCode = NO;
        if (verificationCode && verificationCode.length == 4) {
            checkVerificationCode = YES;
        }
        
        if(checkCusNewTel && checkVerificationCode) {
            return @(YES);
        }
        return @(NO);
    }];
    
    // 获取验证码 按钮是否可以点击
    RAC(self,codeButtonEnabled) = [RACSignal combineLatest:@[RACObserve(self, cusNewTel)] reduce:^id (NSString *cusNewTel){
        
        BOOL checkCusNewTel = NO;
        if (cusNewTel && cusNewTel.length == 11) {
            checkCusNewTel = YES;
        }
        // 如果验证码正在倒计时，则 获取验证码 按钮依然不能点击
        NSRegularExpression *numberRegular = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
        NSInteger count = [numberRegular numberOfMatchesInString:self.codeButtonTitleString options:NSMatchingReportProgress range:NSMakeRange(0, self.codeButtonTitleString.length)];
        if (count > 0) return @(NO);
        
        if(checkCusNewTel) {
            return @(YES);
        }
        return @(NO);
    }];
    
}


/// 检查字段是否有值
-(void)checkStatusThatGoNext {
    RAC(self,goNextStatus) = [RACSignal combineLatest:@[RACObserve(self, houseInfo),
                                                        RACObserve(self, userName),
                                                        RACObserve(self, PersonalIdLastSix)]
                                               reduce:^id (NSString *houseInfo,
                                                           NSString *userName,
                                                           NSString *PersonalIdLastSix){
        
        BOOL checkHouseInfo = NO;
        if (houseInfo && houseInfo.length > 0 && ![houseInfo isEqualToString:@"请选择"]) {
            checkHouseInfo = YES;
        }
        
        BOOL checUserName = NO;
        if (userName && userName.length > 0) {
            checUserName = YES;
            //判断用户名是否全是空格
            if ([userName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length == 0) {
                checUserName = NO;
            }
        }
        
        BOOL checPersonalIdLastSix = NO;
        if (PersonalIdLastSix && PersonalIdLastSix.length == 6) {
            checPersonalIdLastSix = YES;
        }
        
        if (checkHouseInfo && checUserName && checPersonalIdLastSix) {
            return @(YES);
        }
        return @(NO);
    }];
}

#pragma mark - Private Methods
// 发送短信验证码
-(void)sendSMSWithType:(SEGCusAuthorVerificationCodeType)type tel:(NSString *)tel didSubscribe:(id<RACSubscriber>  _Nonnull)didSubscribe{
    [self verificationCodeTimerCountWithType:type];
    
    [[SEGSendsmscodenoimgcodeManager sharedManager] requestSendsmscodenoimgcodeWithTel:tel
                                                                          businessCode:@"C_PROPERTY_AUTH"
                                                                               organId:[SEGProfileManager sharedManager].profile.organId
                                                                           accountCode:kAppPlatformCode
                                                                              finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            [self.messageSubject sendNext:@{@"type":@"2",@"value":errorMessage}];
        }
        [didSubscribe sendCompleted];
    }];
}
/// 短信验证码倒计时逻辑
-(void)verificationCodeTimerCountWithType:(SEGCusAuthorVerificationCodeType)type{
    [[[[[[RACSubject interval:1 onScheduler:[RACScheduler mainThreadScheduler]] startWith:[NSDate date]] scanWithStart:@(60) reduce:^id _Nullable(NSNumber*  _Nullable running, NSDate * _Nullable next) {
        return @( running.integerValue - 1);
    }] takeUntilBlock:^BOOL(NSNumber*  _Nullable x) {
        return x.integerValue < 0;
    }] map:^id _Nullable(id  _Nullable value) {
        
        NSString *codeString = [NSString  string];
        if (type == SEGCusAuthorVerificationCodeTypeDefault) codeString = [NSString  stringWithFormat:@"%@s可重发",value];
        if (type == SEGCusAuthorVerificationCodeTypeNewTel) codeString = [NSString  stringWithFormat:@"%@s重新获取",value];
        return  codeString;
        
    }] subscribeNext:^(id  _Nullable x) {
        self.codeButtonTitleString = x;
        self.codeButtonEnabled = NO;
    }completed:^{
        self.codeButtonEnabled = YES;
        if (type == SEGCusAuthorVerificationCodeTypeDefault) self.codeButtonTitleString = @"重新发送";
        if (type == SEGCusAuthorVerificationCodeTypeNewTel) {
            self.codeButtonTitleString = @"获取验证码";
            if (self.cusNewTel.length != 11) {
                self.codeButtonEnabled = NO;
            }
        }
    }];
}

-(NSString*)messageFromCode:(NSString*)code{
    NSString *msg = @"";
    if ([code isEqualToString:@"-30002"]) msg = @"业主已认证\n不能重复申请认证";
    return msg;
}
#pragma mark - Getter
-(RACSubject *)messageSubject{
    if (!_messageSubject) {
        _messageSubject = [RACSubject subject];
    }
    return _messageSubject;
}
-(SEGQuerycustomerlistbyhouseidResultlistModel *)CusInfo{
    if (!_CusInfo) {
        _CusInfo = [[SEGQuerycustomerlistbyhouseidResultlistModel alloc] init];
    }
    return _CusInfo;
}
#pragma mark - Stter
@end
